package com.leetcode.LC;

public class LC160 {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode n1 = headA, n2 = headB;
        while (!(n1 == null && n2 == null)) {
            if (n1.val != n2.val) {
                n1 = n1.next;
                n2 = n2.next;
            } else {
                return n1;
            }
            if (n1 == null && n2 == null) {
                break;
            }
            if (n1 == null) {
                n1 = headB;
            }
            if (n2 == null) {
                n2 = headA;
            }
        }

        while (n1 != n2) {

            if (n1 == null) {
                n1 = headB;
            } else {
                n1 = n1.next;
            }
            if (n2 == null) {
                n2 = headA;
            } else {
                n2 = n2.next;
            }
        }
        return n1;
    }
}
